<template>
  <div style="text-align: left;">
    <router-link to="/home"><el-i class="fas fa-home" style="color: black;"></el-i></router-link> 
  </div>
  <div class="post-list">
    <el-row>
      <el-col :span="24">
        <!-- 标签筛选 -->
        <div class="filter-tags">
          <el-radio-group v-model="selectedTag" @change="handleTagChange">
            <el-radio label="全部">全部</el-radio>
            <el-radio v-for="tag in tags" :key="tag" :label="tag">{{ tag }}</el-radio>
          </el-radio-group>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading">
          <el-icon class="is-loading"><loading /></el-icon>
          加载中...
        </div>

        <!-- 帖子列表 -->
        <div v-else-if="posts.length > 0" class="post-list-content">
          <div v-for="post in paginatedPosts" :key="post.PostID" class="post-item">
            <h2 class="post-title">
              {{ post.PostTitle }}
              <!-- 标签部分 -->
              <el-tag
                v-for="tag in post.Tags"
                :key="tag.TagName"
                type="info"
                class="post-tag"
              >
                {{ tag.TagName }}
              </el-tag>
            </h2>
            <!-- 添加点击事件 -->
            <p class="post-content" @click="handlePostClick(post.PostID)">
              {{ post.PostContent.length > 40 ? post.PostContent.slice(0, 40) + '......' : post.PostContent }}
            </p>
            <p class="post-meta">
              <span><strong>发布者ID:</strong> {{ post.Post_UserID }}</span>
              <span><strong>专栏:</strong> {{ formatColumns(post.Columns) }}</span>
              <span><strong>发布时间:</strong> {{ post.Post_Date }}</span>
            </p>
          </div>
        </div>

        <!-- 无数据状态 -->
        <div v-else class="no-data">暂无帖子</div>
      </el-col>
    </el-row>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="filteredPosts.length"
        :page-size="pageSize"
        :current-page="currentPage"
        :disabled="loading"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { ElRow, ElCol, ElTag, ElIcon, ElPagination, ElRadioGroup, ElRadio } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import instance from '../api/server';

export default {
  components: {
    ElRow,
    ElCol,
    ElTag,
    ElIcon,
    ElPagination,
    ElRadioGroup,
    ElRadio,
    Loading,
  },
  setup() {
    const posts = ref([]); // 所有帖子数据
    const filteredPosts = ref([]); // 过滤后的帖子数据
    const tags = ref([]); // 标签数据
    const selectedTag = ref('全部'); // 当前选中的标签
    const loading = ref(false); // 加载状态
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(3); // 每页显示的帖子数量
    const router = useRouter();

    // 获取帖子数据
    const getPosts = async () => {
      loading.value = true;
      try {
        const response = await instance.get('/myinfo/blog/getallpost');
        if (response.data?.status === 0 && Array.isArray(response.data.data)) {
          posts.value = response.data.data.map((post) => ({
            ...post,
            Tags: splitStringToArray(post.TagNames, 'TagName'),
            Columns: splitStringToArray(post.ColumnNames, 'ColumnName'),
          }));
          filteredPosts.value = posts.value; // 初始化过滤后的帖子数据
        } else {
          console.error('获取帖子失败:', response.data?.message || '数据格式不正确');
        }
      } catch (error) {
        console.error('获取帖子数据失败:', error.message || error);
      } finally {
        loading.value = false;
      }
    };

    // 获取标签数据
    const getTags = async () => {
      try {
        const response = await instance.get('/myinfo/blog/tag');
        if (response.data?.status === 0 && Array.isArray(response.data.data)) {
          tags.value = response.data.data.map((tag) => tag.TagName);
        } else {
          console.error('获取标签失败:', response.data?.message || '数据格式不正确');
        }
      } catch (error) {
        console.error('获取标签数据失败:', error.message || error);
      }
    };

    // 根据选中的标签过滤帖子
    const filterPostsByTag = () => {
      if (selectedTag.value === '全部') {
        filteredPosts.value = posts.value;
      } else {
        filteredPosts.value = posts.value.filter((post) =>
          post.Tags.some((tag) => tag.TagName === selectedTag.value)
        );
      }
      currentPage.value = 1; // 重置页码
    };

    // 处理标签变化
    const handleTagChange = () => {
      filterPostsByTag();
    };

    // 计算当前页的帖子数据
    const paginatedPosts = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return filteredPosts.value.slice(start, end);
    });

    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page;
    };

    // 处理帖子点击事件
    const handlePostClick = (postId) => {
      router.push(`/bokeinfo/${postId}`);
    };

    // 格式化专栏名称
    const formatColumns = (columns) => {
      return columns.map((column) => column.ColumnName).join(', ');
    };

    // 将字符串按逗号分隔为对象数组
    const splitStringToArray = (str, key) => {
      if (!str) return [];
      return str.split(',').map((item) => ({ [key]: item.trim() }));
    };

    // 组件挂载时加载数据
    onMounted(() => {
      getPosts();
      getTags();
    });

    return {
      posts,
      filteredPosts,
      tags,
      selectedTag,
      loading,
      currentPage,
      pageSize,
      paginatedPosts,
      handlePageChange,
      handleTagChange,
      handlePostClick,
      formatColumns,
    };
  },
};
</script>

<style scoped>
  .post-list {
    display: flex;
    flex-direction: column;
    height: 100vh; /* 设置页面高度为视口高度 */
    padding: 20px;
    box-sizing: border-box;
  }

  .post-list-content {
    flex: 1;
    overflow-y: auto; /* 允许内容区域滚动 */
  }

  .post-item {
    margin-bottom: 20px;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fff;
    transition: box-shadow 0.3s ease;
  }
  
  .post-item:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .post-title {
    font-size: 18px;
    margin-bottom: 10px;
  }
  
  .post-tag {
    margin-left: 10px;
  }
  
  .post-content {
    font-size: 14px;
    color: #666;
    margin-bottom: 10px;
  }
  
  .post-meta {
    font-size: 12px;
    color: #999;
  }
  
  .post-meta span {
    margin-right: 15px;
  }
  
  .loading {
    text-align: center;
    font-size: 14px;
    color: #999;
  }
  
  .no-data {
    text-align: center;
    font-size: 14px;
    color: #999;
  }

  .pagination-container {
    position: fixed;
    bottom: 10px; /* 距离底部100px */
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 10px 20px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    z-index: 1000;
  }

  .pagination {
    text-align: center;
  }
</style>